// user.js模块
// 导出
import { createStore, StoreOptions } from "vuex";
import { UserControllerService } from "../../generated";

export default {
  namespaced: true, // 为每个模块添加一个前缀名，保证模块命明不冲突
  state: () => ({
    loginUser: {
      userName: "未登录",
    },
  }),
  mutations: {
    updateUserName(state, value: string) {
      state.loginUser.userName = value;
    },
    updateUserRole(state, value: string) {
      state.loginUser.userRole = value;
    },
    refreshLoginUser(state, payload) {
      state.loginUser = payload;
    },
  },
  actions: {
    updateUser({ commit, state }, payload) {
      if (payload.userName) {
        commit("updateUserName", payload.userName);
      }
      if (payload.userRole) {
        commit("updateUserRole", payload.userRole);
      }
      console.log("updateUser执行", state.loginUser);
    },
    async refreshLoginUser({ commit, state }) {
      const res = await UserControllerService.getLoginUserUsingGet();
      if (res.code === 0) {
        commit("refreshLoginUser", res.data);
      } else {
        commit("refreshLoginUser", {
          ...state.loginUser,
          userRole: undefined,
        });
      }
    },
  },
} as StoreOptions<any>;
